package com.young.cloud.gateway.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import com.young.common.util.CommonConstants;
import com.young.common.util.CommonUtil;
import com.young.common.util.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 公共的前置处理过滤器
 * Created by Administrator on 2019/12/28 0028.
 */
@Component
public class CommonPreFilter extends ZuulFilter {
    private static final Logger logger = LoggerFactory.getLogger(CommonPreFilter.class);
    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() throws ZuulException {

        //上下文
        RequestContext ctx = RequestContext.getCurrentContext();
        //请求
        HttpServletRequest request = ctx.getRequest();
        //响应
        HttpServletResponse response = ctx.getResponse();

        //获取traceId
        String traceId = request.getParameter(CommonConstants.TRACE_KEY);//参数形式传入traceId
        if (StringUtils.isBlank(traceId)) {
            traceId = request.getHeader(CommonConstants.TRACE_KEY);//请求头方式传入traceId
        }
        if (StringUtils.isBlank(traceId)) {
            traceId = CommonUtil.getUUID();//使用uuid作为traceId
        }

        //设置MDC,日志打印时输出,方便跟踪请求
        MDC.put(CommonConstants.TRACE_KEY, traceId);

        //写入响应头, 传回前端
        response.setHeader(CommonConstants.TRACE_KEY, traceId);

        //写入请求头传给下游服务
        ctx.addZuulRequestHeader(CommonConstants.TRACE_KEY, traceId);

        logger.debug("[网关前置过滤器] 创建分布式链路traceId={}", traceId);
        return null;
    }
}
